/**
 * 
 */
package it.rainbowbreeze.polygen.ui;

import java.util.ArrayList;

import it.rainbowbreeze.polygen.R;
import it.rainbowbreeze.polygen.common.AppEnv;
import it.rainbowbreeze.polygen.common.LogFacility;
import it.rainbowbreeze.polygen.data.ItemsDao;
import it.rainbowbreeze.polygen.domain.ListItem;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author rainbowbreeze
 *
 */
public class CategoriesFragment extends ListFragment {
    private static final String LOG_HASH = CategoriesFragment.class.getSimpleName();
    
    private LogFacility mLogFacility;
    private ItemsDao mItemsDao;
    private ArrayList<ListItem> mItemsToDisplay;
    private ListItemAdapter mItemsAdapter;
    private boolean mFirstRun = true;
    
    // Container Activity must implement this interface
    public interface OnCategorySelectedListener {
        public void onCategorySelected(String category);
    }
    OnCategorySelectedListener mListener;
    
    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        AppEnv appEnv = AppEnv.i(getActivity().getApplicationContext());
        mLogFacility = appEnv.getLogFacility();
        mItemsDao = appEnv.getItemsDao();
        mItemsToDisplay = new ArrayList<ListItem>();
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fracategories, container, false);
        
        mItemsAdapter = new ListItemAdapter(getActivity().getApplicationContext(), mItemsToDisplay);
        setListAdapter(this.mItemsAdapter);
        if (mFirstRun) {
            mLogFacility.v(LOG_HASH, "Loading new level");
            loadNewLevel(0, 0);
            mFirstRun = false;
        }

        return v;
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnCategorySelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        if (null != mListener) {
            ListItem listItem = (ListItem) l.getItemAtPosition(position);
            
//            ListItem listItem = mItemsDao.getItem(id);
            
            //switch to new section
            if (listItem.isCategory()) {
                loadNewLevel(listItem.getParentId(), listItem.getId());
                
            //back one level
            } else if (listItem.isBackItem()) {
                mLogFacility.v(LOG_HASH, "Item name: " + listItem.getName() + ", id: " + listItem.getId() + ", parentId: " + listItem.getParentId());
                loadNewLevel(0, listItem.getParentId());

            //show the item
            } else {
                mListener.onCategorySelected(listItem.getUrl());
            }
        }
    }
    
    private void loadNewLevel(long previousParentId, long currentParentId) {
        mItemsToDisplay.clear();
        //one back at the top...
        if (0 != currentParentId) {
            mItemsToDisplay.add(new ListItem(previousParentId, getString(R.string.common_msgBackToOneLevel)));
        }
        mItemsToDisplay.addAll(mItemsDao.getChildItems(currentParentId));
        //...and one back at the bottom
        if (0 != currentParentId) {
            mItemsToDisplay.add(new ListItem(previousParentId, getString(R.string.common_msgBackToOneLevel)));
        }
        mItemsAdapter.notifyDataSetChanged();
        
        //move to the first item of the list
        try {
            ListView listview = getListView();
            if (listview.getFirstVisiblePosition() > 0 || listview.getLastVisiblePosition() <= 0) {
                listview.smoothScrollToPosition(0);
            }
        } catch (Exception e) {
            //During first initialization of the view, the previous code throws an exception
        }
        
        //TODO save current category
    }
    
    
    /**
     * Custom Adapter for webcam and category list
     * @author rainbowbreeze
     *
     */
    private class ListItemAdapter extends ArrayAdapter<ListItem> {
        private ArrayList<ListItem> mItems;
        LayoutInflater mLayoutInflater;

        public ListItemAdapter(Context appContext, ArrayList<ListItem> items) {
                super(appContext, R.layout.vwlistitem, items);
                this.mItems = items;
                mLayoutInflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        /* (non-Javadoc)
         * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    v = mLayoutInflater.inflate(R.layout.vwlistitem, null);
                }
                ListItem itemToDisplay = mItems.get(position);
                if (itemToDisplay != null) {
                    //set description of item
                    TextView txtItemName = (TextView) v.findViewById(R.id.listitem_txtItemName);
                    if (txtItemName != null) {
                          txtItemName.setText(itemToDisplay.getName());
                    }
                    //show/hide category elements
                    ImageView imgView = (ImageView) v.findViewById(R.id.listitem_imgFolder);
                    if (imgView != null) imgView.setVisibility(itemToDisplay.isCategory() ? View.VISIBLE : View.GONE);
                    imgView = (ImageView) v.findViewById(R.id.listitem_imgBack);
                    if (imgView != null) imgView.setVisibility(itemToDisplay.isBackItem() ? View.VISIBLE : View.GONE);
                }
                return v;
        }
        
        @Override
        public long getItemId(int position) {
            return mItems.get(position).getId();
        }
    }


    /**
     * Simulates the pression on back button
     * @return
     */
    public boolean goBack() {
        ListItem listItem = (ListItem) getListView().getItemAtPosition(0);
        mLogFacility.v(LOG_HASH, "Item name: " + listItem.getName() + ", id: " + listItem.getId() + ", parentId: " + listItem.getParentId());
        if (listItem.isBackItem()) {
            loadNewLevel(0, listItem.getParentId());
            return true;
        } else {
            return false;
        }
    }
}
